<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/11/12
 * Time: 下午1:45
 */

namespace Modules\Admin\Main\Controllers;

use App\Http\Controllers\Controller;
use App\Models\RechargeOrder;
use App\Models\RechargeOrderDetail;
use App\Models\User;
use App\Models\Pay;
use App\Models\UserCoupon;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Modules\Admin\Auth\Facades\AdminAuth;

class MemberController extends Controller
{
    public function index()
    {
        return view('main::member', \Request::all());
    }

    public function map()
    {
        return view('main::user_map',\Request::all());
    }

    public function mapdata(Request $request)
    {
        $datetime = $request->input('datetime');
        $data = [];
        $start_time = time()-3600*24*30;
        $end_time = time();

        if($datetime){
            if(isset($datetime[0])){
                $start_time = strtotime($datetime[0]);
            }
            if(isset($datetime[1])){
                $end_time = strtotime($datetime[1]);
            }
        }

        $start_time = date('Y-m-d 00:00:00',$start_time);
        $end_time = date('Y-m-d 23:59:59',$end_time);

        $result = User::query()->whereBetween('created_at',[$start_time,$end_time])
            ->groupBy('datefield')->select(DB::raw('date(created_at) as datefield,count(*) as total'))
            ->get();

        $orders = RechargeOrder::query()->where('status','>',0)
            ->whereBetween('created_at',[$start_time,$end_time])
            ->groupBy('datefield')->select(DB::raw('date(created_at) as datefield,count(*) as total'))
            ->pluck('total','datefield');

        $datefields = [];
        $userdata = [];
        $orderdata = [];
        foreach($result as $row){
            $datefields[] = $row['datefield'];
            $userdata[] = $row['total'];
            $orderdata[] = isset($orders[$row['datefield']]) ? $orders[$row['datefield']] : 0;
        }



        $items = [
            ['name'=>'用户注册数','type'=>'line','stack'=>'','data'=>$userdata],
            ['name'=>'用户充值数','type'=>'line','stack'=>'','data'=>$orderdata],
        ];

        $data['items'] = $items;
        $data['datefields'] = $datefields;
        return success($data);
    }

    public function reportData()
    {
        $stat = [
            'total_users'           => User::count(),
            'total_recharge_users'  => User::where('recharge_amount', '>', 0)->count(),
            'total_pay_amount'      => Pay::where('is_paid', 1)->sum('amount'),
            'total_recharge_amount' => RechargeOrderDetail::sum('amount') +
                RechargeOrder::where('type', 2)->where('status', '>', '0')->sum('recharge_amount'),
            'total_wait_amount'     => RechargeOrderDetail::where('is_paid', 0)->sum('amount') +
                RechargeOrder::where('type', 2)->whereIn('status', [1,2])->sum('recharge_amount'),
            'total_amount_one'     => RechargeOrderDetail::where('is_paid', 1)->sum('amount') +
                RechargeOrder::where('type', 2)->whereIn('status', [3])->sum('recharge_amount'),
            'total_coupon_one' => UserCoupon::count(),
            'total_coupon_used'=>UserCoupon::where('status',2)->count(),
            'total_coupon_amount' => UserCoupon::where('status',2)->sum('amount')
        ];

        \Request::merge(['stat' => $stat]);

        return view('main::report_data', \Request::all());
    }

    public function channel()
    {
        return view('main::channel', \Request::all());
    }

    public function all(Request $request)
    {
        $limit = $request->input('limit', 10); // 这个是接受参数
        // $limit = 20;
        $offset = $request->input('offset', 0);

        $type = $request->input('type');
        $keyword = $request->input('keyword');
        $datetime = $request->input('datetime');
        $is_channel = $request->input('is_channel', 0);

        $channel  = $request->input('channel','all');//渠道
        $recharge = $request->input('recharge','all');//套餐
        $market   = $request->input('market','all');
        $platform = $request->input('platform','all');

        $recharge_datetime = $request->input('recharge_datetime');

        $query = User::query();

        if($datetime){
            if(isset($datetime[0])){
                $start_time = strtotime($datetime[0]);
                $datetime[0] = date('Y-m-d 00:00:00',$start_time);
            }
            if(isset($datetime[1])){
                $end_time = strtotime($datetime[1]);
                $datetime[1] = date('Y-m-d 23:59:59',$end_time);
            }

        }

        if($recharge_datetime){
            if(isset($recharge_datetime[0])){
                $start_time = strtotime($recharge_datetime[0]);
                $recharge_datetime[0] = date('Y-m-d 00:00:00',$start_time);
            }
            if(isset($recharge_datetime[1])){
                $end_time = strtotime($recharge_datetime[1]);
                $recharge_datetime[1] = date('Y-m-d 23:59:59',$end_time);
            }

        }


        $query = $query->where(function($q) use ($type, $keyword, $datetime,$recharge_datetime, $is_channel) {
            if ($type == 'parent_code' && $keyword) {
                $q->whereHas('parent', function($q) use ($keyword) {
                    $q->where('open_code', $keyword);
                });
            }
            if ($type == 'parent_id' && $keyword){
                $q->whereHas('parent',function ($q) use($keyword){
                    $q->where('id',$keyword);
                });
            }
            if ($type == 'parent_mobile' && $keyword){
                $q->whereHas('parent',function ($q) use($keyword){
                   $q->where('mobile',$keyword);
                });
            }
            if ($type == 'id' && $keyword) {
                $q->where('id', $keyword);
            }
            if ($type == 'mobile' && $keyword) {
                $q->where('mobile', $keyword);
            }
            if ($datetime && isset($datetime[0]) && isset($datetime[1])) {
                //$q->whereBetween('created_at', $datetime);
                $q->where('created_at','>=',$datetime[0])->where('created_at','<=',$datetime[1]);
            }

            if ($recharge_datetime && isset($recharge_datetime[0]) && isset($recharge_datetime[1])) {
                //$q->whereBetween('created_at', $datetime);
                $q->where('first_recharge_time','>=',$recharge_datetime[0])->where('first_recharge_time','<=',$recharge_datetime[1]);
            }

            if ($is_channel) {
                $q->where('is_channel', 1);
            } else {
                $q->where('is_channel', 0);
            }
        });

        if($platform !== 'all'){
            $query = $query->where('app_platform',$platform);
        }

        if($market !== 'all'){
            $query = $query->where('app_channel',$market);
        }

        if($channel !== 'all'){
            $parent_id = (new User())->query()->where('open_code',$channel)->value('id');
            $query = $query->where('parent_id',$parent_id);
        }

        $data['total'] = $query->count();
        $data['amount_total'] = $query->sum('recharge_amount');

        $data['items'] = $query->with('parent')->take($limit)
            ->skip($offset)
            ->orderBy('id', 'desc')
            ->get();


        if ($is_channel) {
            $items = [];
            foreach ($data['items'] as &$item) {
                $items[] = [
                    'id' => $item->id,
                    'open_code' => $item->open_code,
                    'nickname' => $item->nickname,
                    'mobile' => $item->mobile,
                    'is_channel' => $item->is_channel,
                    'member_total' => User::where('parent_id', $item->id)->count(),
                    'recharge_amount_total' => User::where('parent_id', $item->id)->sum('recharge_amount'),
                    'invite_url' => 'http://h5.wenhuakj.com/spreadNew?invite_code=' . $item->open_code

                ];
            }
            $data['items'] = $items;
        }

        foreach($data['items'] as $key=>$item){
//            $item['mobile'] = AdminAuth::user()->is_super ? $item['mobile'] : $item['mobile'];
            $item['mobile_en'] = encrypt($item['mobile']);
//            $item['mobile'] = convert_mobile($item['mobile']);
            $data['items'][$key] = $item;
        }

        $data['recharge_total'] = $query->where('recharge_amount','>',0)->count();

        return success($data);
    }

    // public function link()
    // {
    //     $link = $request->input('link');
        
    // }

    public function store(Request $request)
    {
        $nickname = $request->input('nickname');
        if (!$nickname) {
            return fail(400, '表单填写不全');
        }

        $mobile = '111' . rand(1000, 9999) . rand(1000, 9999);

        User::create([
            'nickname' => $nickname,
            'mobile' => $mobile,
            'open_code' => rand(1000, 9999) . substr($mobile, -4, 4),
            'app_platform' => '',
            'app_version' => '',
            'open_id' => '',
            'is_channel' => 1,
        ]);

        return success();
    }

    public function couponList(Request $request)
    {
        return view('main::user_coupon',$request->all());
    }

    public function searchCouponList(Request $request)
    {
        $data = ['total'=>0,'items'=>[]];
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $field = $request->input('field');
        $value = $request->input('keyword');
        $status = intval($request->input('status',0));

        $query = UserCoupon::query();

        if($field && $value){
            if($field=='user_id'){
                $query = $query->where('user_id',$value);
            }
            if($field=='mobile'){
                $user = User::query()->where('mobile',$value)->first();
                if(!$user){
                    return success($data);
                }
                $query = $query->where('user_id',$user->id);
            }
        }

        if($status > 0){
            $query = $query->where('status',$status);
        }


        $data['total'] = $query->count();
        $data['items'] = $query->with('user')->take($limit)->skip($offset)->orderBy('id', 'desc')->get();
        return success($data);
    }

    public function sendCoupon(Request $request)
    {
        $coupon_id = $request->input('coupon_id');
        $user_id   = $request->input('user_id');
        if($coupon_id && $user_id){
            UserCoupon::sendCouponToUser($coupon_id,$user_id);
        }
        return success();
    }
}